#include "ip_utils.hpp"
#include <sstream>
#include <regex>

namespace ip_utils {

uint32_t inetAtoN(const std::string& ip) {
    if (!isValidIp(ip)) {
        return 0;
    }
    
    std::istringstream iss(ip);
    std::string segment;
    uint32_t result = 0;
    
    while (std::getline(iss, segment, '.')) {
        result = (result << 8) | static_cast<uint8_t>(std::stoi(segment));
    }
    
    return result;
}

std::string inetNtoA(uint32_t ip) {
    std::stringstream ss;
    ss << ((ip >> 24) & 0xFF) << "."
       << ((ip >> 16) & 0xFF) << "."
       << ((ip >> 8) & 0xFF) << "."
       << (ip & 0xFF);
    return ss.str();
}

bool isValidIp(const std::string& ip) {
    std::regex ip_pattern("^(\\d{1,3}\\.){3}\\d{1,3}$");
    if (!std::regex_match(ip, ip_pattern)) {
        return false;
    }
    
    std::istringstream iss(ip);
    std::string segment;
    
    while (std::getline(iss, segment, '.')) {
        int num = std::stoi(segment);
        if (num < 0 || num > 255) {
            return false;
        }
    }
    
    return true;
}

} // namespace ip_utils 